package com.dc.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CharSetFilter",urlPatterns="/*",initParams = {@WebInitParam(name="encoding",value="utf-8")})

public class CharSetFilter implements Filter {
    String encoding;
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化参数");
        encoding=filterConfig.getInitParameter("encoding");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了编码过滤器");
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        if(encoding!=null){
            response.setCharacterEncoding(encoding);
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset="+encoding);
            filterChain.doFilter(request,response);
        }
    }

    public void destroy() {
        System.out.println("销毁");
    }
}


